package top.jybill.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.jybill.dao.IOrderDao;
import top.jybill.dao.IOrderTravellerDao;
import top.jybill.domain.MyPageInfo;
import top.jybill.domain.Order;
import top.jybill.domain.Traveller;
import top.jybill.exception.MyException;
import top.jybill.service.IOrderService;
import top.jybill.utils.CharCodeUtil;

import java.util.List;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class IOrderServiceImpl implements IOrderService {

  @Autowired
  private IOrderDao orderDao;
  @Autowired
  private IOrderTravellerDao orderTravellerDao;

  public MyPageInfo findOrdersByPage(MyPageInfo pageInfo) {
    // 转UTF-8
    pageInfo.setQuery(CharCodeUtil.getUTF8CharCode(pageInfo.getQuery(), "UTF-8"));

    if (pageInfo.getQuery().length() < 1 || "null".equalsIgnoreCase(pageInfo.getQuery())) {
      pageInfo.setQuery(null);
    } else {
      pageInfo.setQuery("%" + pageInfo.getQuery() + "%");
    }

    PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
    List<Order> orders = orderDao.findOrdersByPage(pageInfo);
    return new MyPageInfo(orders);
  }

  public Order findOrderDetailById(String id) {
    // check
    if (id == null || id.length() < 1) {
      throw new MyException("id不正确");
    }
    return orderDao.findOrderById(id);
  }

  /**
   * 删除订单
   * @param oid
   */
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  public void delOrder(String oid) {
    // check与旅客多对多关联
    List<Traveller> travellers = orderTravellerDao.findTravellerByOid(oid);

    // 删除多对多
    if (travellers != null) {
      orderTravellerDao.delOrderTraveller(oid); // 删除操作
    }

    // 删除订单
    orderDao.delOrderByOid(oid);
  }
}
